<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>热力图-立体仓储系统</title>
	<!--<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>-->
	<link rel="stylesheet" href="css/all.min.css">
	<link rel="stylesheet" href="css/index.css">
    <script src="js/jquery-3.7.1.min.js"></script>
	<script src="js/index.js"></script>
	<script src="js/data-wms.js"></script>
    <style>	
		
		
		
		/* 内容区样式 */
		.view-title {
			margin:10px 0px 5px;0px;
			color:#fff;
			font-weight: bold;
			padding-left: 10px;
		}
		.view-title .fas {
			cursor: pointer;
			margin-right: 8px;
			transition: transform 0.3s;
		}
		
        .view-container {
            display: flex;
            flex-direction: column;
            gap: 0px;
        }

        .rack-group {
            display: flex;
            gap: 15px;
            padding: 3px;
			align-items: center;
            border: 0px solid #ddd;
        }
        .group-title {
			white-space: nowrap;
            color: #90e0ef;
            text-align: center;
			width: 30px;
			flex-shrink: 0;
        }

        .row {
            display: flex;
            gap: 1px;
            justify-content: center;
        }
        .rack {
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid rgba(255, 255, 255, 0.2);
            transition: all 0.3s;
            flex-shrink: 0;
            font-size: 14px;
            position: relative;
        }
		.rack.exists {cursor: pointer; background-color: rgba(255, 255, 255, 0.2); } /* 该位置存在库位 */
        
		.dwelltime {
            margin-left: 60px;
        }
		
    </style>
</head>
<body>
	<!-- 导航栏 -->
    <div id="floating-nav">
        <div class="nav-collapsed"></div>
        <div class="nav-content">
            <div class="nav-icon" data-tooltip="库存监控" data-url="wms-2d.html">
                <i class="fas fa-chart-bar"></i>
            </div>
            <div class="nav-icon nav-icon-active" data-tooltip="热力图" data-url="heatmap.html">
                <i class="fas fa-braille"></i>
            </div>
            <div class="nav-icon" data-tooltip="数据同步" data-url="data-sync.html">
                <i class="fas fa-exchange"></i>
            </div>
        </div>
    </div>
	<div class="title">
	<div class="summary-container">
        <div class="storage-selector">
            <select id="storageSelect">
                <option value="D">国内存储区</option>
                <option value="I">国际存储区</option>
            </select>
        </div>
		<div class="summary-stats">根据[使用次数/停留时间]的热力图</div>
		
		<div class="view-control">
			<i title="侧/俯视图" class="fa-solid fa-list active"></i>
			<a href="heatmap-3d.html"><i title="三维视图" class="fa-solid fa-cube"></i></a>
		</div>
    </div>
		<div class="screen-control" id="fullscreen-component">
			<i class="fas fa-expand fullscreen-toggle" title="进入全屏"></i>
		</div>
	</div>
    <div class="filter">
        <div class="view-switcher">
            <div class="view-btn" data-mode="layer">
                <i title="按层查看(俯视图)" class="fa-solid fa-layer-group"></i>
            </div>
            <div class="view-btn active" data-mode="row">
                <i title="按排查看(侧视图)" class="fa-solid fa-clone"></i>
            </div>
        </div>
        <div id="filterContainer"></div>
    </div>
	<div>
		<div style = "color: #fff;float:left;margin-left:400px;">使用次数</div>
		<div style = "color: #fff;float:left;margin-left:650px;">停留时间</div>
	</div>

    <div id="warehouseDisplay" class="scrollable-container"></div>

    <script>
		// 库位热力数据 注意最大255，以255来平均
		
		// 货架数据定义（X列-Y层-Z排） status:1存在 0不存在
		//const coord = { x: 20, y: 5, z: 10 };
        let racks = [];
        (function initracks() {
            for(let z=1; z<=coord.z; z++) {
                for(let y=1; y<=coord.y; y++) {
                    for(let x=1; x<=coord.x; x++) {
						const w=warehouses.find(w => `${w.coordW[0]}-${w.coordW[1]}-${w.coordW[2]}` === `${x}-${y}-${z}`);
                        racks.push({
                            coordinate: `${x}-${y}-${z}`,
                            coordinateX: x,
                            coordinateY: y,
                            coordinateZ: z,
                            status: w ? 1 : 0,
							spaceNo:w ? w.spaceNo : ""
                        });
                    }
                }
            }
        })();
		
		
		
		// 初始化视图切换
        $(function() {
			$('#warehouseDisplay').on('click', '.view-title .fas', function() {
				$(this).closest('.view-title').next('.view-container').slideToggle(300);
				$(this).toggleClass('fa-caret-right fa-caret-down');
			});
			$('#storageSelect').on('change', function() {
                // 变化事件函数留空
            });
			
            $('.view-btn').click(function() {
                $('.view-btn').removeClass('active');
                $(this).addClass('active');
                updateFilter();
            });
            
            updateFilter();
        });

        function getViewMode() {
            return $('.view-btn.active').data('mode');
        }
		

        function updateFilter() {
			const viewMode = getViewMode();
            
            $('#filterContainer').html(`${viewMode === 'layer' ? '按层查看' : '按排查看'}`);
            
            updateDisplay();
        }

        function updateDisplay() {
            const viewMode = getViewMode();
            $('#warehouseDisplay').empty();
			
			const params = viewMode === 'layer' ? coord.y : coord.z;
			const label = viewMode === 'layer' ? `层` : `排`;
			for(let i=params;i>0;i--){
				var param = i;
				$('#warehouseDisplay').append("<div class='view-title'><i class='fas fa-caret-down'></i>"+param+label+"</div>");
				updateDisplay2(param);
			}
			
			updateHot();//更新库位状态
			updateDwelltime();
        }
		function updateDisplay2(param) {
            const viewMode = getViewMode();
            // 筛选数据
            const filtered = racks.filter(item => 
                viewMode === 'layer' ? item.coordinateY == param : item.coordinateZ == param
            );

            // 分组处理
            const groups = {};
            filtered.forEach(item => {
                const groupKey = viewMode === 'layer' ? item.coordinateZ : item.coordinateY;
                groups[groupKey] = groups[groupKey] || [];
                groups[groupKey].push(item);
            });

            // 创建视图
            const viewContainer = $('<div>').addClass('view-container');
            
            Object.keys(groups).sort((a,b) => b - a).forEach(groupKey => {
                const groupDiv = $('<div>').addClass('rack-group');
                
                // 组标题
                $('<div>')
                    .addClass('group-title')
                    .text(viewMode === 'layer' ? `${groupKey}排` : `${groupKey}层`)
                    .appendTo(groupDiv);

                // 库位行
                const rowDiv = $('<div>').addClass('row usedtime');//使用次数
				const rowDiv2 = $('<div>').addClass('row dwelltime');//停留时间
                
                groups[groupKey]
                    .sort((a,b) => a.coordinateX - b.coordinateX)
                    .forEach(item => {
                        const $rack = $('<div>')
								.addClass(`rack ${item.status ? 'exists' : ''}`)
								.text(item.status ? item.coordinateX: '')
								.attr('data-coordinate',`${item.coordinate}`)
								.attr('data-spaceNo',`${item.spaceNo}`)
								.attr('title', 
									`货架坐标：${item.coordinate}\n` +
									`货架状态：${item.status ? '库位' : '无库位'}`
								);
						$rack.appendTo(rowDiv);
						$rack.clone().appendTo(rowDiv2);
                    });
                
                groupDiv.append(rowDiv);
				groupDiv.append(rowDiv2);
                viewContainer.append(groupDiv);
            });

            $('#warehouseDisplay').append(viewContainer);
        }
		// 更新库位热力
		function updateHot(){
			//根据使用次数分组并排序
			const groupedWarehouse= warehouses.reduce((acc,item)=>{
				if(!acc[item.usedTimes]){
					acc[item.usedTimes]=[];
				}
				acc[item.usedTimes].push(item);
				return acc;
			},{});
			console.log(groupedWarehouse);
			const sortedGroupedWarehouse = Object.keys(groupedWarehouse).sort((a, b) => b - a);;
			console.log(sortedGroupedWarehouse);
			
			var nameToIndexMap = {};
			for(let i =0;i<sortedGroupedWarehouse.length;i++){
				const count = sortedGroupedWarehouse[i];
				groupedWarehouse[count].forEach(item=>{
					nameToIndexMap[item.spaceNo] = { count: parseInt(count), index: i+1 };
				});
			}
			console.log(nameToIndexMap);
			
			const red = 255;
			var green = 0;
			const blue = 0;
			//组数255-0, 均匀到255
			for(let i =0;i<sortedGroupedWarehouse.length;i++){
				const count = sortedGroupedWarehouse[i];
				groupedWarehouse[count].forEach(item=>{
					green=Math.min(255,Math.floor(255/sortedGroupedWarehouse.length *(i+1)));
					//green=i>255?255:i;
					$(`.usedtime [data-spaceNo="${item.spaceNo}"]`)
					.css("background-color",`rgba(${red}, ${green}, ${blue}, 0.6)`)
					.attr('title', 
						`库位编号：${item.spaceNo}\n` +
						`使用次数：${count}`
					)
				});
			}
		}
		function updateDwelltime(){
			//根据停留时间分组并排序
			const groupedWarehouse= warehouses.reduce((acc,item)=>{
				if(!acc[item.dwellTime]){
					acc[item.dwellTime]=[];
				}
				acc[item.dwellTime].push(item);
				return acc;
			},{});
			console.log(groupedWarehouse);
			const sortedGroupedWarehouse = Object.keys(groupedWarehouse).sort((a, b) => b - a);;
			console.log(sortedGroupedWarehouse);
			
			var nameToIndexMap = {};
			for(let i =0;i<sortedGroupedWarehouse.length;i++){
				const count = sortedGroupedWarehouse[i];
				groupedWarehouse[count].forEach(item=>{
					nameToIndexMap[item.spaceNo] = { count: parseInt(count), index: i+1 };
				});
			}
			console.log(nameToIndexMap);
			
			const red = 255;
			var green = 0;
			const blue = 0;
			//组数255-0, 均匀到255
			for(let i =0;i<sortedGroupedWarehouse.length;i++){
				const count = sortedGroupedWarehouse[i];
				groupedWarehouse[count].forEach(item=>{
					green=Math.min(255,Math.floor(255/sortedGroupedWarehouse.length *(i+1)));
					//green=i>255?255:i;
					$(`.dwelltime [data-spaceNo="${item.spaceNo}"]`)
					.css("background-color",`rgba(${red}, ${green}, ${blue}, 0.6)`)
					.attr('title', 
						`库位编号：${item.spaceNo}\n` +
						`停留时间：${count}`
					)
				});
			}
		}
		// 更新库位状态
		function updateState(){
			const maxUsage=Math.max(...warehouses.map(x => x.usedTimes));
			const minUsage=Math.min(...warehouses.map(x => x.usedTimes));
			const calcUsage=maxUsage-minUsage;//跨度多少个255
			console.log(maxUsage+","+minUsage);
			$('.view-container .rack.exists').each(function(index,element){
				//console.log($(element).attr('data-coordinate'));
				var usedTimes=0;
				var spaceNo = $(element).attr('data-spaceNo');
				const ws = warehouses.find(w => w.spaceNo === spaceNo);
				if(ws){
					usedTimes = ws.usedTimes;
				}else{
					// 未知状态
				}
				const red = 255;//Math.min(255,Math.floor((usedTimes-minUsage)/calcUsage * 255));
				const green = Math.max(0,Math.floor((1-(usedTimes-minUsage)/calcUsage) * 255));
				const blue = 0;
				$(element).css("background-color",`rgba(${red}, ${green}, ${blue}, 0.6)`);
				$(element).attr('title', 
					`库位编号：${spaceNo}\n` +
					`使用次数：${usedTimes}`
				)
			});
		}
    </script>
</body>
</html>